//
// Created by denglibin on 19-10-24.
//

/**
 *文件锁(多个进程操作同一个文件) 使用fcntl
 **/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

static int main_(void){

    int fd;
    struct flock f_lock;
    char * fileName = "test.txt";
    fd = open(fileName, O_RDWR | O_CREAT);
    if(fd < 0){
        perror("open:");
        exit(-1);
    }
    f_lock.l_type = F_RDLCK;// 读锁
    //f_lock.l_type = F_WRLCK;// 写锁
    f_lock.l_whence = SEEK_SET;
    f_lock.l_start = 0;
    f_lock.l_len = 0; //0表示整个文件加锁

    fcntl(fd, F_SETLK, &f_lock); // 加锁
    sleep(1);

    f_lock.l_type = F_UNLCK;
    fcntl(fd, F_SETLKW, &f_lock);//释放锁
    close(fd);
    unlink(fileName);
    return 0;
}




